package com.cellulam.api.config.filters;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * content-type
 */
@Component
@Slf4j
public class ContentTypeFilter extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getMethod().equals(HttpMethod.OPTIONS.name())) {
            return true;
        }

        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.hasMethodAnnotation(RequestMapping.class)) {
                RequestMapping requestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
                if (requestMapping.consumes().length <= 0 ||
                        requestMapping.produces().length <= 0) {
                    response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                }
            }
        }

        return true;
    }
}
